/*
 * main.c
 *
 *  Created on: 16/12/2011
 *      Author: marciocs5
 */

#include <stdlib.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../graph/graph.h"
#include "../solver/formulation.h"
#include "../solver/solver.h"

long k;
long* va;

int main(int argc, char** argv){

	long ndcnt, ndlst;
	printf("Programa para Problema de Recoloração de Vértices \n");
	if(argc < 3){
		printf("Numero Inválido de argumentos \n");
	}
	FILE* graphFile = fopen(argv[1], "r");
	k = atoi(argv[2]);
	if (graphFile == NULL) {
		printf("Could not open %s.\n", argv[1]);
		return 0;
	}
	int code = loadSharedGraph(graphFile, GT_COMPLEMENT);
	fclose(graphFile);
	setAdjMatrix(getSharedGraph());

	int* cover = malloc(sizeof(int)*nverts());
	printf("Arquivo %s e k = %lu \n", argv[1], k);
	va = malloc(sizeof(long)*nverts());

	mcrStableSort(nverts(), cover);
	//printf("cover sort sem problemas\n");
	//fflush(NULL);

	/*printf("GRAFO e k = %d\n", k);
	for(i = 0; i < nverts(); i++){
		for(j = i+1; j < nverts(); j++){
			if(!hasEdge(va[i], va[j])) printf("aresta %d %d \n",va[i], va[j]);
		}
	}*/

	//medição do tempo
	struct timespec start, end;
	double elapsed;
    struct timeval tv;
    gettimeofday(&tv, NULL);
    start.tv_sec = tv.tv_sec;
    start.tv_nsec = tv.tv_usec * 1000;

    //cria a formulação
    createFormulation();
	printf("criei a formulação\n");
	fflush(NULL);

    //resolve a formulação
    double sol =  solve(&ndcnt, & ndlst);
	printf("resolvi o problema\n");
	fflush(NULL);

	gettimeofday(&tv, NULL);
	end.tv_sec = tv.tv_sec;
	end.tv_nsec = tv.tv_usec * 1000;

	elapsed = (end.tv_sec - start.tv_sec);
	elapsed += (end.tv_nsec - start.tv_nsec) / 1000000000.0;
	printf("Tempo Gasto: %8.5g secundos(s).\n", elapsed);
	printf("Solução encontrada = %f \n", sol);
	printf("Número de Nós visitados = %lu \n", ndcnt);
	printf("Último nó inteiro = %lu \n", ndlst);
	FILE* out = fopen("result.txt","a+");
	fprintf(out," %s \t %d \t %d \t %f \t %f \t %lu \n", argv[1], nverts(), nedges(), sol, elapsed, ndcnt);
	fclose(out);
    //imprimi para chegagem a formulação
	//if(printFormulation() != 0)printf("\n PROBLEMAS \n");
	releaseSharedGraph(code);
	freeAdjMatrix();
	return 0;
}

